var macroMode = true, macros = [];

// switchMacroMode();
// 
// $('#results').bind('contextmenu', function (event)
// {
// 	clearResults();
// 	
// 	return false;
// });

// /////////////////
// Handle Macro Mode
// /////////////////

function switchMacroMode()
{
	macroMode = !macroMode;
	
	$('.not_macroMode, .macroMode').hide();
	$('.' + (macroMode ? '' : 'not_') + 'macroMode').show();
	
	if (macroMode) {
		$('#results').height(98);
	} else {
		$('#results').height(121);
	}
	
	$('#macroModeCheckbox').attr('checked', macroMode);
	
	clearResults();
}

function preToMacro(query)
{
	return $.trim($(query).html()
		.replace(/ • /g, '').replace(/<br>/g, "\n"));
}

function ajouterMacro()
{
	var macro = preToMacro('#results');
	
	macro = macro.replace(
		new RegExp($.trim($('#replace').val()), 'g'), '%%%');
	
	if (macro == '') {
		return false;
	}
	
	jQuery.facebox('\
<h2>Ajouter une Macro :</h2>\
\
<div>Add the following macro:</div>\
<label style="display: block">Description: <input type="text" id="macroDescription" value=""></label><br>\
<pre id="macroToAdd">' + macro + '</pre>\
<button onclick="confirmerAjouterMacro()">Add</button>\
');
	
	switchMacroMode();
}

function confirmerAjouterMacro()
{
	var macro = preToMacro('#macroToAdd'),
		description = $('#macroDescription').val();
	
	if (description === '') {
		alert('Please specify a description.');
		
		return false;
	}
	
	var macroId = macros.push(macro) - 1;
	
	$('#macros').append('<option value="' + macroId + '">' + description + '</option>')
	
	jQuery(document).trigger('close.facebox');
}

function activateMacro()
{
	var idMacro = $('#macros').val();
	
	if (idMacro === '-1') {
		return false;
	}
	
	$('#macros').val('-1');
	
	jQuery.facebox('\
<h2>Execute Macro:</h2>\
\
<div>Execute the following macro:</div>\
<pre>' + macros[idMacro] + '</pre>\
<input id="macroToExecute" type="hidden" value="' + idMacro + '">\
<label style="display: block">Replacement: <input type="text" id="macroReplace" value=""></label><br>\
<button onclick="executeMacro()">Execute</button>\
');
	
	return false;
}

function executeMacro()
{
	jQuery(document).trigger('close.facebox');
	
	$('#request').val(
		macros[$('#macroToExecute').val()]
			.replace(/%%%/g, $('#macroReplace').val()));
	
	(new Action('custom')).execute();
	
	return false;
}
